﻿import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Dialogs 1.2
import QtSensors 5.3
import QtQuick.Window 2.2


ApplicationWindow {
    visible: true
    width: Screen.width
    height: Screen.height
    title: qsTr("小球")


    MainForm{
        id: mainForm
        anchors.fill: parent
        bubble{
            id: bubble
            centerX: mainWindow.width/2
            centerY: mainWindow.height/2
            bubbleCenter: bubble.width/2
            x: bubble.centerX - bubble.bubbleCenter
            y: bubble.centerY - bubble.bubbleCenter

            Behavior on y {
                SmoothedAnimation {
                    easing.type: Easing.Linear
                    duration: 100
                }
            }
            Behavior on x {
                SmoothedAnimation {
                    easing.type: Easing.Linear
                    duration: 100
                }
            }
        }
    }

    Accelerometer{
        id: accel
        dataRate: 100
        active: true

        onReadingChanged: {
            var newX = (mainForm.bubble.x + calcRoll(accel.reading.x, accel.reading.y, accel.reading.z) * 2)
            var newY = (mainForm.bubble.y - calcPitch(accel.reading.x, accel.reading.y, accel.reading.z) * 2)

            if (isNaN(newX) || isNaN(newY))
                return;

            if (newX < 0)
                newX = 0

            if (newX > mainForm.mainWindow.width - mainForm.bubble.width)
                newX = mainForm.mainWindow.width - mainForm.bubble.width

            if (newY < 18)
                newY = 18

            if (newY > mainForm.mainWindow.height - mainForm.bubble.height)
                newY = mainForm.mainWindow.height - mainForm.bubble.height

            mainForm.bubble.x = newX
            mainForm.bubble.y = newY
        }
    }

    function calcPitch(x, y, z) {
        return -(Math.atan(y / Math.sqrt(x * x + z * z)) * 57.2957795);
    }
    function calcRoll(x, y, z) {
        return -(Math.atan(x / Math.sqrt(y * y + z * z)) * 57.2957795);
    }
}

